import React, { useState, useEffect } from 'react';
import { Form, Button, Popover, Progress, message } from 'antd';
import { Link, connect, history, FormattedMessage, useIntl } from 'umi';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import styles from './index.less';

const passwordStatusMap = {
  ok: (
    <div className={styles.success}>
      <FormattedMessage id="pages.register.strength.strong" />
    </div>
  ),
  pass: (
    <div className={styles.warning}>
      <FormattedMessage id="pages.register.strength.medium" />
    </div>
  ),
  poor: (
    <div className={styles.error}>
      <FormattedMessage id="pages.register.strength.short" />
    </div>
  ),
};

const passwordProgressMap = {
  ok: 'success',
  pass: 'normal',
  poor: 'exception',
};

const Register = ({ submitting, dispatch, register }) => {
  const [visible, setVisible] = useState(false);
  const [popover, setPopover] = useState(false);
  const confirmDirty = false;
  const [form] = Form.useForm();
  const intl = useIntl();

  useEffect(() => {
    if (!register) {
      return;
    }

    const account = form.getFieldValue('mail');

    if (register.success) {
      message.success('注册成功！');
      dispatch({
        type: 'register/saveStatus',
        payload: false,
      });
      history.push({
        pathname: '/user/RegisterResult',
        state: {
          account,
        },
      });
    }
  }, [register]);

  const getPasswordStatus = () => {
    const value = form.getFieldValue('password');

    if (value && value.length > 9) {
      return 'ok';
    }

    if (value && value.length > 5) {
      return 'pass';
    }

    return 'poor';
  };

  const onFinish = (values) => {
    dispatch({
      type: 'register/submit',
      payload: { ...values },
    });
  };

  const checkConfirm = (_, value) => {
    const promise = Promise;

    if (value && value !== form.getFieldValue('password')) {
      return promise.reject(
        intl.formatMessage({
          id: 'pages.register.password.twice',
        }),
      );
    }

    return promise.resolve();
  };

  const checkPassword = (_, value) => {
    const promise = Promise; // 没有值的情况

    if (!value) {
      setVisible(!!value);
      return promise.reject(
        intl.formatMessage({
          id: 'pages.register.password.required',
        }),
      );
    } // 有值的情况

    if (!visible) {
      setVisible(!!value);
    }

    setPopover(!popover);

    if (value.length < 6) {
      return promise.reject('');
    }

    if (value && confirmDirty) {
      form.validateFields(['confirm']);
    }

    return promise.resolve();
  };

  const renderPasswordProgress = () => {
    const value = form.getFieldValue('password');
    const passwordStatus = getPasswordStatus();
    return value && value.length ? (
      <div className={styles[`progress-${passwordStatus}`]}>
        <Progress
          status={passwordProgressMap[passwordStatus]}
          className={styles.progress}
          strokeWidth={6}
          percent={value.length * 10 > 100 ? 100 : value.length * 10}
          showInfo={false}
        />
      </div>
    ) : null;
  };

  const renderFormButton = () => {
    return (
      <Form.Item>
        <Button
          size="large"
          loading={submitting}
          className={styles.submit}
          type="primary"
          htmlType="submit"
        >
          <FormattedMessage id="pages.register.register" />
        </Button>
        <Link className={styles.login} to="/user/login">
          <FormattedMessage id="pages.register.signIn" />
        </Link>
      </Form.Item>
    );
  };

  return (
    <div className={styles.main}>
      <h3>
        <FormattedMessage id="pages.register.register" />
      </h3>
      <ProForm
        form={form}
        name="UserRegister"
        onFinish={onFinish}
        submitter={{ render: renderFormButton }}
      >
        <ProFormText
          name="mail"
          placeholder={intl.formatMessage({ id: 'pages.register.mail.placeholder' })}
          rules={[
            {
              required: true,
              message: <FormattedMessage id="pages.register.mail.required" />,
            },
            {
              type: 'email',
              message: <FormattedMessage id="pages.register.mail.wrongFormat" />,
            },
          ]}
          fieldProps={{ size: 'large' }}
        />
        <ProFormText
          name="username"
          placeholder={intl.formatMessage({ id: 'pages.register.username.placeholder' })}
          rules={[
            {
              required: true,
              message: <FormattedMessage id="pages.register.username.required" />,
            },
          ]}
          fieldProps={{ size: 'large' }}
        />
        <Popover
          getPopupContainer={(node) => {
            if (node && node.parentNode) {
              return node.parentNode;
            }

            return node;
          }}
          content={
            visible && (
              <div
                style={{
                  padding: '4px 0',
                }}
              >
                {passwordStatusMap[getPasswordStatus()]}
                {renderPasswordProgress()}
                <div
                  style={{
                    marginTop: 10,
                  }}
                >
                  <FormattedMessage id="pages.register.strength.msg" />
                </div>
              </div>
            )
          }
          overlayStyle={{
            width: 240,
          }}
          placement="right"
          visible={visible}
        >
          <ProFormText.Password
            name="password"
            placeholder={intl.formatMessage({ id: 'pages.register.password.placeholder' })}
            rules={[
              {
                validator: checkPassword,
              },
            ]}
            fieldProps={{ size: 'large' }}
          />
        </Popover>
        <ProFormText.Password
          name="confirm"
          placeholder={intl.formatMessage({
            id: 'pages.register.confirmPassword.placeholder',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'pages.register.confirmPassword.required',
              }),
            },
            {
              validator: checkConfirm,
            },
          ]}
          fieldProps={{ size: 'large' }}
        />
      </ProForm>
    </div>
  );
};

export default connect(({ register, loading }) => ({
  register,
  submitting: loading.effects['register/submit'],
}))(Register);
